//
//  XS_CouponSubVC.swift
//  XueDao
//
//  Created by Mac on 2020/12/26.
//

import UIKit

enum XS_CouponSubVCType {
    case all
    case used
    case nouse
    case select
}

protocol XS_CouponSubVCDelegate {
    func couponSubVC(couponSubVC:XS_CouponSubVC, didSelectCoupon:XS_CouponItemModel)
}

class XS_CouponSubVC: XS_BaseVC {
    
    var delegate : XS_CouponSubVCDelegate?
    
    var type : XS_CouponSubVCType = .all
    var condition = ""
    
    var coupon_id = ""
    
    lazy var couponDataModel = XS_CouponItemM()
    
    lazy var bottomView : XS_CouponBottomView = {
        let bottomView = XS_CouponBottomView.init(frame: CGRect.init(x: 0, y: .screenHeight - .barHeight - 44 - 84, width: .screenWidth, height: 49 + .bottomHeight))
        bottomView.delegate = self
        return bottomView
    }()
    
    var selectModel = XS_CouponItemModel()

    @IBOutlet weak var collectionView: UICollectionView!
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "选择优惠券"
        // Do any additional setup after loading the view.
        collectionView.register(UINib.init(nibName: "XS_CouponItemCell", bundle: Bundle.main), forCellWithReuseIdentifier: "XS_CouponItemCell")
        collectionView.register(UINib.init(nibName: "XS_CouponHeaderView", bundle: Bundle.main), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "XS_CouponHeaderView")
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(headerRefresh))
        collectionView.mj_footer = MJRefreshBackNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(footerRefresh))
        collectionView.mj_footer?.ignoredScrollViewContentInsetBottom = (UIApplication.shared.statusBarFrame.size.height == 44) ? 34 : 0
        headerRefresh()
        if type == .select {
            view.addSubview(bottomView)
            collectionView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: .bottomHeight, right: 0)
        }else{
            collectionView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: .bottomHeight, right: 0)
        }
    }
    
    @objc func headerRefresh(){
        requestData(isFirst: true)
    }
    
    @objc func footerRefresh(){
        requestData(isFirst: false)
    }
    
    func requestData(isFirst : Bool){
//        /coupons/queryAll
        if isFirst {
            couponDataModel.current = 0
            couponDataModel.records.removeAll()
        }
//        "state":"",
//            "isInvalid":"",
        var state = ""
        var isInvalid = ""
        var api = "/coupons/queryAll"
        switch type {
        case .used:
            state = "used"
            break
        case .nouse:
            isInvalid = "invalid"
            break
        case .select:
            api = "/coupons/queryByUpCondition"
            break
        default:
            //
            break
        }
        XS_NetWork.requestJson(api, parameters: ["pageNo" : couponDataModel.current+1, "pageSize" : couponDataModel.size,"state":state,"isInvalid": isInvalid, "condition":condition])
            .mapModel(type: XS_CouponItemM.self) // 返回 模型数组 和原始数据
            .subscribe(onNext: { [weak self] model, resp in
                guard let `self` = self, resp.success, let model = model else {return }
                model.records = self.couponDataModel.records + model.records
                let blankPageView = XD_BlankPageView()
                if model.records.count > 0 {
                    self.bottomView.isHidden = false
                    blankPageView.isHidden = true
                    blankPageView.removeFromSuperview()
                    self.couponDataModel = model
                    if self.coupon_id.count > 0 {
                        for subModel in self.couponDataModel.records {
                            if self.coupon_id == subModel.id {
                                subModel.selected = true
                                self.selectModel = subModel
                                let attr = NSMutableAttributedString.init(string: ("已选1张可减￥" + self.selectModel.money))
                                attr.addAttribute(.font, value: UIFont.systemFont(ofSize: 18), range: NSRange.init(location: "已选1张可减".count, length: ("￥"+self.selectModel.money).count))
                                attr.addAttribute(.foregroundColor, value: UIColor.qmui_color(withHexString: "ED653F")!, range: NSRange.init(location: "已选1张可减".count, length: ("￥"+self.selectModel.money).count))
                                self.bottomView.allLabel.attributedText = attr
                                self.bottomView.operateBtn.backgroundColor = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
                            }
                        }
                    }
                    self.collectionView.reloadData()
                } else {
                    self.bottomView.isHidden = true
                    blankPageView.isHidden = false
                    blankPageView.blankPage(imgName: "缺省页_暂无优惠券", detailStr: "暂无优惠券~", btnTitle: "去首页看看", bottomDetailStr: "") {
                        if let tbc = XS_NVC.shared.viewControllers.first as? XS_TBC {
                            tbc.selectedIndex = 0
                        }
                        XS_NVC.shared.popToRootViewController(animated: true)
                    }
                    blankPageView.frame = CGRect.init(x: 0, y: 84, width: self.collectionView.frame.size.width, height: self.collectionView.frame.size.height - 84)
                    self.collectionView.addSubview(blankPageView)
                }
                self.collectionView.mj_header?.endRefreshing()
                if model.current >= model.pages { // 没有更多
//                    self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
                    self.collectionView.mj_footer?.endRefreshing()
                }else{
                    self.collectionView.mj_footer?.endRefreshing()
                }
            }).disposed(by: disposeBag)
    }
}

extension XS_CouponSubVC : UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return couponDataModel.records.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XS_CouponItemCell", for: indexPath) as! XS_CouponItemCell
        cell.model = couponDataModel.records[indexPath.item]
        cell.canSelect = type == .select
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind:UICollectionView.elementKindSectionHeader , withReuseIdentifier: "XS_CouponHeaderView", for: indexPath) as! XS_CouponHeaderView
        headerView.delegate = self
        return headerView
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize.init(width: .screenWidth - 32, height: 104)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: .screenWidth, height: 84)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 16, left: 16, bottom: 16, right: 16)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 8
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 16
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectModel = couponDataModel.records[indexPath.item]
        let attr = NSMutableAttributedString.init(string: ("已选1张可减￥" + selectModel.money))
        attr.addAttribute(.font, value: UIFont.systemFont(ofSize: 18), range: NSRange.init(location: "已选1张可减".count, length: ("￥"+selectModel.money).count))
        attr.addAttribute(.foregroundColor, value: UIColor.qmui_color(withHexString: "ED653F")!, range: NSRange.init(location: "已选1张可减".count, length: ("￥"+selectModel.money).count))
        bottomView.allLabel.attributedText = attr
        bottomView.operateBtn.backgroundColor = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
        for model in couponDataModel.records {
            model.selected = model.id == selectModel.id
        }
        collectionView.reloadData()
    }
}

extension XS_CouponSubVC : XS_CouponHeaderViewDelegate{
    func headerView(headerView: XS_CouponHeaderView, didClickConvertBtn: UIButton) {
        XS_NetWork.requestJson("/coupons/convertCoupons",parameters: ["exchangeCode":headerView.textField.text!])
            .subscribe(onNext: { resp in //直接返回原始数据 resp.data
                if resp.success{
                    let dataDict = resp.data as! [String:Any]
                    let state = dataDict["state"]
                    let stateStr = state as! String
                   /** 领取优惠券结果状态：
                    null：没有此优惠券，
                    convert：以被领取或兑换，
                    invalid：此优惠券以失效，
                    success：兑换成功 */
                    if stateStr == "success" {
                        self.requestData(isFirst: true)
                        self.view.makeToast("兑换成功")
                    } else if stateStr == "null" {
                        self.view.makeToast("没有此优惠券")
                    } else if stateStr == "convert"{
                        self.view.makeToast("此优惠券已被领取或兑换")
                    } else if stateStr == "invalid"{
                        self.view.makeToast("此优惠券已失效")
                    } else {
                        self.view.makeToast("兑换失败")
                    }
                } else {
                    self.view.makeToast(resp.msg)
                }
            }).disposed(by: disposeBag)
    }
}

extension XS_CouponSubVC : XS_CouponBottomViewDelegate{
    func bottomView(bottomView: XS_CouponBottomView, didClickOperateBtn: UIButton) {
        if delegate != nil {
            delegate?.couponSubVC(couponSubVC: self, didSelectCoupon: selectModel)
            navigationController?.popViewController(animated: true)
        }
    }
}
